// pages/Tabbar/My/My.js
//获取应用实例
const app = getApp()
const assetsAddress = app.globalData.global.assetsIp + '/' + app.globalData.global.assetsName;

import { updateUserNicknameAndAvatar } from '../../../api/user';
import { Login } from '../../../store/user';
import { register } from '../../../api/login';
import { queryUserRate } from '../../../api/reward';

Page({
  // 推广佣金
  mineCommendEarningDetail(){
    wx.navigateTo({
      url: '/pages/Projects/ShareBrokerage/ShareBrokerage',
    })
  },
  // 获取佣金信息
  getProjectRate(){
    let _this = this;
    queryUserRate()
    .then(res => {
      if(res.success){
        _this.setData({
          mineProjectAmount: res.data.projectAward ?? '0.00',
          mineCommendAmount: res.data.spreadAward ?? '0.00',
        })
      }else{
        wx.showToast({
          title: res.errMessage,
          icon: 'none',
        })
      }
    })
  },
  // 项目佣金
  mineProjectEarningDetail(){
    wx.navigateTo({
      url: '/pages/Projects/ProjectBrokerage/ProjectBrokerage',
    })
  },
// footer
bottomAction(event){
  var value = event.currentTarget.dataset.index;
  if(!wx.getStorageSync('token')){
    this.setData({
      showGetPhoneBtn: true,
    })
    return;
  }
  switch (value) {
  case 1:
    wx.navigateTo({
      url:"realName/realName",
    });
    // if(wx.getStorageSync('realNameStatus') != '3'){
    //   wx.navigateTo({
    //     url:"realName/realName",
    //   });
    // }else{
    //   console.log()
    //   wx.showToast({
    //     title: '已实名，无需重复实名',
    //     icon: 'none',
    //   })
    // }
    break;
  case 2:
    wx.navigateTo({
      url:"contracts/contracts",
    });
    break;
  case 3:
    wx.navigateTo({
      url:"bankCard/bankCardList",
    });
    break;
  case 4:
    wx.navigateTo({
      url:"mineTeam/mineTeam",
    });
    break;
  case 5:
    wx.navigateTo({
      url:"/pages/User/IndividualBusiness/IndividualBusiness",
    });
    break;
    default:
      break;
  }

  console.log(value);
},
  /**
   * 页面的初始数据
   */
  data: {
    mineAvatar: wx.getStorageSync('avatar') ? wx.getStorageSync('avatar') : assetsAddress + "/mine/mine_avatar_bg.png",
    nickname: wx.getStorageSync('nickName') ? wx.getStorageSync('nickName') : '点击获取',
    phoneNumber:wx.getStorageSync('mobile') ? wx.getStorageSync('mobile') : '-',
    referrerName:wx.getStorageSync('preUserName') ? wx.getStorageSync('preUserName') : wx.getStorageSync('preMobile') ? wx.getStorageSync('preMobile') : '-',
    mineCommendAmount:"0.00",
    mineProjectAmount:"0.00",
    bottomDatas:[{"index":1,"icon":assetsAddress+"/mine/realname_icon.png","title":"实名认证","des":""},
                 {"index":2,"icon":assetsAddress+"/mine/contract_icon.png","title":"合同签署","des":""},
                 {"index":3,"icon":assetsAddress+"/mine/bank_icon.png","title":"银行卡","des":""},
                 {"index":4,"icon":assetsAddress+"/mine/team_icon.png","title":"我的团队","des":""},
                 {"index":5,"icon":assetsAddress+"/mine/getiIcon.png","title":"个体工商户","des":""}],   
    token: wx.getStorageSync('token'),
    assetsAddress: assetsAddress,
    showGetPhoneBtn: false,
    shareTitle: app.globalData.global.shareTitle,
    userRealnameStatus: '',
    showPrivacyAuthor: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.setStorageSync('toPath', '/pages/Tabbar/My/My');
    this.initPrivacy();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    if(wx.getStorageSync('hasNewUser') == 'true'){
      await Login({noToast: false});
      wx.setStorageSync('hasNewUser', 'falses')
    }
    this.setData({
      token: wx.getStorageSync('token'),
      userRealnameStatus: wx.getStorageSync('realNameStatus'),
      mineAvatar: wx.getStorageSync('avatar'),
      nickname: wx.getStorageSync('nickName'),
      phoneNumber:wx.getStorageSync('mobile')
    })
    if(wx.getStorageSync('token')){
      // 获取数据
      this.getProjectRate();
      // 获取推广佣金

    }
    var _this = this;
    if (wx.onNeedPrivacyAuthorization){
      wx.onNeedPrivacyAuthorization((resolve) => {
        console.log('触发弹窗')
        // 触发弹窗
        _this.setData({
          showPrivacyAuthor: true,
        })
        _this.resolvePrivacyAuthorization = resolve
        console.log(resolve,resolve);
      })
    }  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let userId = wx.getStorageSync('userId')
    return {
      title: this.data.shareTitle,
      path: '/pages/Tabbar/Home/Home?scene='+userId,
    }
  },
  // 获取用户手机号
  getPhoneNumber(e){
    console.log(e.detail.code)
    let _this = this;
    var preUserId = wx.getStorageSync('preUserId');
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          // console.log(res,'res')
          wx.setStorageSync('loginCode', res.code)
          const params = preUserId == '' ? {loginCode: res.code, phoneCode: e.detail.code} : {loginCode: res.code, phoneCode: e.detail.code,preUserId: preUserId}
          register(params)
          .then(async(res1) => {
            if(res1.success){
              await Login({noToast: false});
              // this.triggerEvent('myevent')
              _this.setData({
                token: wx.getStorageSync('token'),
                userRealnameStatus: wx.getStorageSync('realNameStatus'),
                mineAvatar: wx.getStorageSync('avatar'),
                nickname: wx.getStorageSync('nickName'),
                phoneNumber:wx.getStorageSync('mobile')
              })
              _this.getProjectRate();
            }else{
              if(res1.errMessage == '当前手机号已注册' || res1.errMessage == '当前微信已注册'){
                await Login({noToast: false});
                _this.setData({
                  token: wx.getStorageSync('token'),
                  userRealnameStatus: wx.getStorageSync('realNameStatus'),
                  mineAvatar: wx.getStorageSync('avatar'),
                  nickname: wx.getStorageSync('nickName'),
                  phoneNumber:wx.getStorageSync('mobile')
                })
                _this.getProjectRate();
                // this.triggerEvent('myevent')
              }else{
                wx.showToast({
                  title: res1.errMessage,
                  icon: 'none',
                })
              }
            }
          })
        }
      })
  },
  // 获取用户头像和昵称
  getUserInfo(){
    console.log('11')
    if(!this.data.token){
      return;
    }
    console.log('是否直接返回？')
    wx.getUserProfile({
      desc: '用户完善会员资料',
      success: (user) => {
        console.log(user,'用户昵称')
        const params = {
          'userName': user.userInfo.nickName,
          'avatar': user.userInfo.avatarUrl,
        }
        updateUserNicknameAndAvatar(params)
        .then(async (res) => {
          if(res.success){
            await Login({noToast: false});
            this.setData({
              mineAvatar: user.userInfo.avatarUrl,
              nickname: user.userInfo.nickName,
            })
            console.log(this.data.mineAvatar,'mineAvatar')
          }else{
            wx.showToast({
              title: res.errMessage,
              icon: 'none',
            })
          }
        })
      },
      fail:(err) =>{
        console.log(err,'err')
      }
    })
  },
  onClose(){},
  handleAgreePrivacyAuthorizationFun(){
    console.log('同意之后的回调');
  },
  disagreePrivacyAuthorization(){
    this.resolvePrivacyAuthorization({ event: 'disagree' });
  },
  initPrivacy(){
    wx.requirePrivacyAuthorize({
      success: () => {
        // 用户同意授权
        // 继续小程序逻辑
      },
      fail: () => {}, // 用户拒绝授权
      complete: () => {}
    })
  },
})